<?php
  include('data/lib_f_pictures.inc.php');
  include('data/v_global.inc.php'); # Override standard values
  include('data/lib_components.inc.php');  
  $content = '';
  
  /** 
  * A member updated their details.
  */
  if ($_POST['member_submitted']) 
  {
      include('data/lib_f_validate.inc.php');
      extract($_POST);
      if($newpw) 
	  {
        $setpw = false;  
        if (md5($oldpw) == mqs("SELECT Password FROM members WHERE MID=".$MID)) {
            $setpw = true;  
        } else $err .= 'Old password incorrect.<br>';
        if ($setpw) {
            if ($newpw != $newpw2) $err .= 'Password and re-typed Password mismatch. Please type again.';
        }
      }
	  /**
	  * Email
	  **/
      if (!$eMail = validateEmail($eMail)) 
	  {
          $err .= 'eMail address invalid.<br>';
          $eMail = $_POST['eMail']; # Restore old invalid value.
      }
	  
      /**
      * Pic upload
      **/
      if ($_FILES['newpic']['name'] && !$keep_newpic) {
         $_FILES['newpic']['name'] = $memberpicprefix.substr(md5(time()),0,7).'_'.$MID.'.jpg';
         if (uploadPicture($_FILES['newpic'],MEMBERPICDIR,$validpictypes,$maximgheight,$maximgwidth,$maximgsize,$picmsg)) {
            if ($Pic && $Pic != $_FILES['newpic']['name']) {
                deletePic(MEMBERPICDIR.$Pic);
            }
            $Pic = $_FILES['newpic']['name'];
            createThumb(MEMBERPICDIR.$Pic,$thumbwidth,$thumbheight);
         } else $err .= $picmsg;
     }
	 
    /**
	 * UCmember and ID
	 */
	if($UCmember)
	{
		if(!$SID = validateText($SID))
		{
			$err .= 'Student ID is invalid!<br>';
			$SID = $_POST['SID'];
		}
	}
	
	/** 
	 * All the other fun validations...
	 */
	if($Phone && !$Phone = validateText($Phone)){$err .= 'Phone number is invalid!<br>';$Phone = $_POST['Phone'];}
	if($EmergencyPhone && !$EmergencyPhone = validateText($EmergencyPhone)){$err .= 'Emergency phone number is invalid!<br>';$EmergencyPhone = $_POST['EmergencyPhone'];}
	if($Allergies && !$Allergies = validateText($Allergies)){$err .= 'Allergies text is invalid!<br>';$Allergies = $_POST['Allergies'];}
	if($Address1 && !$Address1 = validateText($Address1)){$err .= 'Address line 1 is invalid!<br>';$Address1 = $_POST['Address1'];}
	if($Address2 && !$Address2 = validateText($Address2)){$err .= 'Address line 2 is invalid!<br>';$Address2 = $_POST['Address2'];}
 
     if (!$err)
	 {
		$query = "UPDATE `members` SET ";
		$query .= ($setpw ? "Password ='".md5($newpw)."',":'');
		$query .= " eMail='".$eMail."', Pic='".$Pic."'";
		$query .= ($UCmember ? ", UCmember=".$UCmember.", SID=".$SID : ", UCmember=0, SID=NULL");
		$query .= ", Phone='".$Phone."', EmergencyPhone='".$EmergencyPhone."'";
		$query .= ", sex='".$sex."', Allergies='".$Allergies."', Address1='".$Address1."', Address2='".$Address2."'";
		$query .= ", send_news=" . ($send_news ? "1 " : "0 ");
		$query .= ", news_social=" . ($news_social ? "b'1' " : "b'0' ");
        $query .= ", news_polo=" . ($news_polo ? "b'1' " : "b'0' ");
        $query .= ", news_river=" . ($news_river ? "b'1' " : "b'0' ");
        $query .= ", news_surf=" . ($news_surf ? "b'1' " : "b'0' ");
        $query .= ", send_notes=" .($send_notes ? "1 ": "0 ");
        $query .= ", instructor=" .($instructor ? "1 ": "0 ");
        $query .= ", second=" .($second ? "1 ": "0 ");
		$query .= " WHERE MID=".$MID;
        if($res = mq( $query ) )
         {$content .= 'Settings successfully changed.<br><br>';} else { $content .= 'Please tell webmaster that something went wrong with the mysql query: '.$query.' <br>' . $res .'<br>'.$err ;}
     } else $content .= $err.'<br><br>';
      
  /**
  * A Webmaster edited club members 
  */
  } else if ($_POST['submitted']) {
        include('data/lib_f_bits.inc.php');
        /**
        * Process existing members
        */
        if ($res = mq("SELECT MID FROM members")) {
            while ($data = mysql_fetch_row($res)) {
                $MID = $data[0];
                $rights = 0;
                if ($_POST['WM_'.$MID]) setBit($rights,$r_webmaster);
                if ($_POST['Com_'.$MID]) setBit($rights,$r_comittee);
                mq("UPDATE members SET Rights=$rights WHERE MID=$MID");
            }
        }
        
        /**
        * New member
        * Must be after existing members as otherwise the rights are resetted!
        */
        if ($_POST['newmember']) {
            include('data/lib_f_validate.inc.php');
            if ($email = validateEMail($_POST['newmember_eMail'])) {
                $rights = 0;
                if ($_POST['WM_newmember']) setBit($rights,$r_webmaster);
                if ($_POST['Com_newmember']) setBit($rights,$r_comittee);
                include('data/class.phpmailer.php');
                createMember($_POST['newmember'],substr(md5(time()),0,5),$email,$rights);
            } else $content .= 'Invalid eMail address: "'.$_POST['newmember_eMail'].'"<br>';
        }
        
        
  } else if ($_GET['del'] && ($_SESSION['rights'] & $r_webmaster)) 
  {
    mq("DELETE FROM members WHERE MID=".$_GET['del']);
  }
  
  /**
  * Create content. Only done if someone is logged in!
  */
  if ($_SESSION['logged']) 
  {
      /**
      * Display current logged in user details
      */
      if( ($_SESSION['rights'] & $r_webmaster) && !isset($_SESSION['subtopic']) || $_SESSION['subtopic'] == 'profile' || !($_SESSION['rights'] & $r_webmaster) || ($_SESSION['rights'] & $r_webmaster && $_SESSION['subtopic'] == 'member'))
      {
          $wb = ($_SESSION['rights'] & $r_webmaster && $_SESSION['subtopic'] == 'member');
          
          if ($data = mqs("SELECT * FROM members WHERE MID=".($wb?($_GET['member_MID']?$_GET['member_MID']:mqs("SELECT MID FROM members LIMIT 1")):$_SESSION['MID'])))
          {
            extract($data);
		    if($wb)
            {
              $content .= '<table width="80%"><tr><td>';
              if($last_member = mqs("SELECT MID FROM `members` WHERE MID < " .$MID. " ORDER BY MID DESC LIMIT 1"))
              {
                  $content .='<a href="'.$_SERVER['PHP_SELF'].'?topic=member&subtopic=member&member_MID='.$last_member.'">Previous Member</a>';
              }
              $content .= "</td><td>";
              if($next_member = mqs("SELECT MID FROM `members` WHERE MID > " .$MID. " ORDER BY MID ASC LIMIT 1"))
              {
                  $content .='<a href="'.$_SERVER['PHP_SELF'].'?topic=member&subtopic=member&member_MID='.$next_member.'">Next Member</a>';
              }
              $content .= "</td></tr></table>";
            }
            
            /* Silly check box code... will be a better way to do this! */
            $check_box = 'checked="checked"';
            if($instructor){$instructor = $check_box;}else{$instructor = " ";}
            if($second){$second = $check_box;}else{$second = " ";}
            if($UCmember){$UCcheck = $check_box;}else{$UCcheck = " ";}
		    if($send_news){$send_news = $check_box;}else{$send_news = " ";}
		    if($send_notes){$send_notes = $check_box;}else{$send_notes = " ";}
            if($news_social==1){$news_social = $check_box;}else{$news_social = " ";}
            if($news_river==1){$news_river = $check_box;}else{$news_river = " ";}
            if($news_polo==1){$news_polo = $check_box;}else{$news_polo = " ";}
            if($news_surf==1){$news_surf = $check_box;}else{$news_surf = " ";}
            
		    if($sex == "M"){$male = 'checked="checked"'; $female =" ";} else {$female = 'checked="checked"'; $male =" ";}
		    
            $content .= '<i>Details Last Updated:'.$updated.'</i><br><hr>Here you can see and edit your membership details:
					    
                        <br>
                        <form action="'.$_SERVER['PHP_SELF'].'" method="POST" enctype="multipart/form-data">
                        <table cellpadding="3">
                          <tr><td>Name</td><td><b>'.$Name.'</b></td></tr>
                          <tr>'.($wb ? '<td><b>Instructor </b><input name="instructor" type="checkbox" id="instructor" value="true" '. $instructor.' /></td><td><b>Second</b><input name="second" type="checkbox" id="second" value="true" '.$second.' /></td>':'').'</tr>
                          <tr><td>Sex</td><td><table width="250"><tr><td><input name="sex" type="radio" value="M" '.$male.' />male</td><td><input name="sex" type="radio" value="F" '.$female.'  />female</td></tr></table></td></tr>
					      <tr><td>email</td><td><input type="text" class="text" name="eMail" value="'.$eMail.'" size="20"></td></tr>
                          <tr><td>Phone Number</td><td><input type="text" class="text" name="Phone" value="'.$Phone.'" size="20" /></td></tr>
                          <tr><td>Enable newsletters</td><td><input name="send_news" type="checkbox" id="send_news" value="true" '. $send_news.' /></td></tr>
                          <tr><td>Receive Social Events Newsletters</td><td><input name="news_social" type="checkbox" id="news_social" value="true" '. $news_social.' /></td></tr>
                          <tr><td>Receive Whitewater Newsletters</td><td><input name="news_river" type="checkbox" id="news_river" value="true" '. $news_river.' /></td></tr>
					      <tr><td>Receive Polo Newsletters</td><td><input name="news_polo" type="checkbox" id="news_polo" value="true" '. $news_polo.' /></td></tr>
                          <tr><td>Receive Surf Newsletters</td><td><input name="news_surf" type="checkbox" id="news_surf" value="true" '. $news_surf.' /></td></tr>
                          <tr><td>Receive Messages from board?</td><td><input name="send_notes" type="checkbox" id="send_notes" value="true" '.$send_notes.' /></td></tr>
					      <tr><td>UC Member</td><td><input name="UCmember" type="checkbox" id="UCmember" value="true" '. $UCcheck.' /></td></tr>
                          <tr><td>UC Student ID</td><td><input type="text" class="text" name="SID" value="'.$SID.'" size="20" /></td></tr>
                          <tr><td>Emergency Phone</td><td><input type="text" class="text" name="EmergencyPhone" value="'.$EmergencyPhone.'" size="20" /></td></tr>
                          <tr><td>Address</td><td><input name="Address1" type="text" class="text" value="'.$Address1.'" size="45" maxlength="100" /></td></tr>
                          <tr><td>Address 2</td><td><input name="Address2" type="text" class="text" value="'.$Address2.'" size="45" maxlength="100" /></td></tr>
                          <tr><td><p>Allergies &amp; Medications</p></td><td><textarea name="Allergies" cols="45" rows="5" wrap="virtual" class="text" id="Allergies">'.$Allergies.'</textarea></td></tr>
					      <tr><td>New Password</td><td><input type="password" class="text" name="newpw" size="20"></td></tr>
                          <tr><td>Repeat Password</td><td><input type="password" class="text" name="newpw2" size="20"></td></tr>                      
                          <tr><td>Old Password</td><td><input type="password" class="text" name="oldpw" size="20"></td></tr>
                          <tr><td>Pic</td><td>'.PicUploadForm($Pic,'Pic','newpic',MEMBERPICDIR,20).'</td></tr>
					      <tr><td>Date Joined: </td><td>'.(($_SESSION['rights'] & $r_webmaster) ? datepicker($newdate,$joined) : DBDate2Date($joined) ).'</td></tr>
					      <tr><td>done?</td><td><input type="submit" class="button" value="submit" size="20" /></td></tr>
                        </table>
                        <input type="hidden" name="member_submitted" value="1">
                        <input type="hidden" name="MID" value="'.$MID.'">
                        </form>';
          }
      }

      /**
      * List all members.
      * Only visible to members with webmaster rights.
      */
      if( $_SESSION['rights'] & $r_webmaster && $_SESSION['subtopic'] == 'members')
      {
          if ( $res = mq("SELECT * FROM members ORDER BY Rights DESC,Name")) 
          {
              $content .= '<br>
                          As webmaster you are also eligible to edit members:<br>
                          <form action="'.$_SERVER['PHP_SELF'].'" method="POST">
                          <table cellpadding="2"><tr><th>Del</th><th>Name, Email, Date Joined</th><th>Rights: <br><i>Webmaster  Committee</i></th>';
              while ($data = mysql_fetch_array($res)) {
                  extract($data);
                  settype($Rights,'integer');
                  $content .= '<tr><td><a href="'.$_SERVER['PHP_SELF'].'?del='.$MID.'" onClick="return confirm(\'REALLY delete member?\')"><img src="'.BILDERDIR.'del.gif" alt="del"></a></td>
                                   <td><a href="'.$_SERVER['PHP_SELF'].'?topic=member&subtopic=member&member_MID='.$MID.'">'.limitText($Name,30).'</a><br>'.limitText($eMail,30).'<br>'.DBDate2Date($joined).'</td>
                                   <td nowrap>
                                      <input type="checkbox" name="WM_'.$MID.'" value="'.$r_webmaster.'" '.($Rights & $r_webmaster ? 'checked':'').'>WM<br>
                                      <input type="checkbox" name="Com_'.$MID.'" value="'.$r_comittee.'" '.($Rights & $r_comittee ? 'checked':'').'>Com
                                   </td>
                               </tr>';
              }
              $content .= '<tr><td>Add:</td>
                               <td><input type="text" class="text" name="newmember" size="20"> name<br>
                                   <input type="text" class="text" name="newmember_eMail" size="20"> eMail</td>
                               <td>
                                 <input type="checkbox" name="WM_newmember" value="1">WM
                                 <input type="checkbox" name="Com_newmember" value="1">Com
                               </td></tr>
                           <tr><td colspan="3" style="text-align:center">
                               <input type="submit" class="button" value=" submit ">
                               <input type="hidden" name="submitted" value="1"></td></tr>
                           </table></form>';
          }
      }   
  }
?>                                                      